/*************************************************************************
 * Copyright 2008 David Almilli
 *  
 * Licensed under the Apache License, Version 2.0 (the "License"); 
 * you may not use this file except in compliance with the License. 
 * You may obtain a copy of the License at 
 *  
 *     http://www.apache.org/licenses/LICENSE-2.0 
 *      
 * Unless required by applicable law or agreed to in writing, software 
 * distributed under the License is distributed on an "AS IS" BASIS, 
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 
 * See the License for the specific language governing permissions and 
 * limitations under the License.
 **************************************************************************/
package com.tivo.hme.bananas;

import com.tivo.hme.interfaces.ILogger;
import com.tivo.hme.sdk.View;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;

public class PlusSupport {
    private PlusSupport() {}
    
    /**
     * Calls viewRemoveNotify on the view and all child views recursively.
     */
    public static void viewRemoveNotify(View parent) {
        try {
            Method method = parent.getClass().getDeclaredMethod("viewRemoveNotify");
            int mods = method.getModifiers();
            if (Modifier.isPublic(mods) || Modifier.isProtected(mods)) {
                //only call public and protected methods
                method.setAccessible(true);
                method.invoke(parent);
            }
        } catch (NoSuchMethodException e) {
            //it isn't disposable
        } catch (Exception e) {
            //ignore, we tried
            parent.getApp().log(ILogger.LOG_DEBUG, 
                    "Error calling viewRemoveNotify on view " + parent);
        }

        //notify each child recursively
        View child;
        int count = parent.getChildCount();
        for (int i=0; i < count; i++) {
            child = parent.getChild(i);
            viewRemoveNotify(child);
        }
    }
    
    /*

    private static Object invoke(Object obj, String name) {
        return invoke(obj, name, null);
    }

    private static Object invoke(Object obj, String name, Class[] types, Object... args) {
        try {
            Method method = obj.getClass().getMethod(name);
            method.setAccessible(true);
            return method.invoke(obj, args);
        } catch (Exception e) {
            throw new RuntimeException("Cannot invoke method " + name + " from " + obj);
        }
    }
    
    private static Field getField(Class cls, String name) {
        Field field = null;
        try {
            field = cls.getDeclaredField(name);
            field.setAccessible(true);
        } catch (Exception e) {
            throw new RuntimeException("Cannot read field " + name + " from " + cls);
        }
        return field;
    }
    */
}
